//
//  YWToningView.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/8/20.
//

#import "YWToningView.h"

@interface YWToningView ()

//原始view
@property(nonatomic,strong)UIImageView *bgImageView;

/** 要绘制的图片 */
@property (nonatomic, strong) UIImage * ogrinalImage;

@property(nonatomic,strong)UIView *colorView;

@property(nonatomic,assign)CGFloat red;//0-1
@property(nonatomic,assign)CGFloat green;//0-1
@property(nonatomic,assign)CGFloat blue;//0-1

@end

@implementation YWToningView

-(UIView *)colorView{
    
    if(_colorView == nil){
        _colorView = [[UIView alloc] init];
    }
    return _colorView;
}

-(UIImageView *)bgImageView{
    if(_bgImageView == nil){
        UIImageView *bgImageView = [[UIImageView alloc] init];
        _bgImageView = bgImageView;
    }
    return _bgImageView;
}

//纯代码用这个
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

//xib用这个
-(void)awakeFromNib{
    [super awakeFromNib];
    [self setup];
}

//初始化
-(void)setup{
    [self addSubview:self.bgImageView];
    self.clipsToBounds = YES;
    [self addSubview:self.colorView];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    self.bgImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    self.colorView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}

//设置初始图片
- (void)setFirstImage:(UIImage *)image{
    
    _ogrinalImage = image;
    
    self.bgImageView.image = image;
    
}

-(void)setRedColor:(CGFloat)red{
    self.red = red;
    self.colorView.backgroundColor = [UIColor colorWithRed:self.red green:self.green blue:self.blue alpha:[self getAlpha]];
    
}
-(void)setGreenColor:(CGFloat)green{
    self.green = green;
    self.colorView.backgroundColor = [UIColor colorWithRed:self.red green:self.green blue:self.blue alpha:[self getAlpha]];
    
}
-(void)setBlueColor:(CGFloat)blue{
    self.blue = blue;
    self.colorView.backgroundColor = [UIColor colorWithRed:self.red green:self.green blue:self.blue alpha:[self getAlpha]];
}

-(CGFloat)getAlpha{
    CGFloat alpha = 0;
    if(self.red == 0 && self.green == 0 && self.blue == 0){
        alpha = 0;
    }
    else{
        alpha = 0.1;
    }
    return alpha;
    
}

//获取当前图层
-(UIImage *)getCurrentLayer{
    //1.开启一个位图上下文
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
    
    //2.把画板上的内容渲染到上下文当中
    CGContextRef ctx =  UIGraphicsGetCurrentContext();
    [self.layer renderInContext:ctx];
    
    //3.从上下文当中取出一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //4.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}
@end
